﻿using System;
using System.Data;
using System.Collections.Generic;
using YiYiTong.Rocket.Helper;
using YiYiTong.Rocket.Entity;
using YiYiTong.Rocket.Model;
using YiYiTong.Rocket.DataAccess;
using YiYiTong.Rocket.EFDBFirst;
using System.Web;
using System.Linq;
using YiYiTong.Rocket.Business.Biz;

namespace YiYiTong.Rocket.Business
{
    public class JingjiaBiz
    {
        #region 单例模式
        private JingjiaBiz()
        {
        }

        private static JingjiaBiz _instance;
        private static readonly object _syncObject = new object();

        public static JingjiaBiz Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (_syncObject)
                    {
                        if (_instance == null)
                        {
                            _instance = new JingjiaBiz();
                        }
                    }
                }
                return _instance;
            }
        }
        #endregion 单例模式


        /// <summary>
        /// 竞价列表查询
        /// </summary>
        /// <param name="label_type">1 直播 2 预热 3 爆款</param>
        /// <param name="brand_id">品牌id</param>
        /// <param name="category_id">分类id</param>
        /// <param name="selKey">搜索关键字</param>
        /// <returns></returns>
        public Tuple<bool, JingjiaListModel> GetList(long jingjia_config_id, long uid, long brand_id, long category_id, string selKey, int pageIndex, int pageRows)
        {
            DataSet ds = JingjiaDataAccess.Instance.GetJingjiaList(jingjia_config_id, uid, brand_id, category_id, selKey, pageIndex, pageRows);
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[1].Rows.Count > 0)
            {
                ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
                var jingjiaConfig = dbcontext.ADZ_JingjiaConfig.FirstOrDefault(t => t.jingjia_config_id == jingjia_config_id);

                JingjiaListModel model = new JingjiaListModel();
                model.list = new ModelHandler<JingjiaModel>().FillModel(ds.Tables[1]);
                model.allrows = ConvertHelper.ConvertTo<int>(ds.Tables[0].Rows[0]["allrows"]);
                model.allpages = ConvertHelper.ConvertTo<int>(ds.Tables[0].Rows[0]["allpages"]);

                if (model.list != null && model.list.Any())
                {
                    model.list.ForEach(t =>
                    {
                        t.img_url = SysConfigBiz.Instance.GetThingIMG(t.img_url);
                        if (t.last_price <= 0)
                        {
                            if (t.base_price > 0)
                                t.last_price = t.base_price;
                            else
                                t.last_price = t.step_price;
                        }
                        t.baoming_counts = jingjiaConfig.baoming_counts;
                        t.baozheng_price = jingjiaConfig.baozheng_price;
                        t.begin_time = jingjiaConfig.begin_time;
                        if (!t.real_end_time.HasValue)
                        {
                            t.real_end_time = jingjiaConfig.end_time;
                        }
                    });
                }

                List<long> jingjia_ids = (from t in model.list
                                          select t.jingjia_id).ToList();


                //是否报名
                var baomings = dbcontext.ADZ_JingjiaBaomingOrder.Where(t => t.jingjia_config_id == jingjia_config_id && t.uid == uid && t.is_succ == 1).ToList();
                if (baomings.Any())
                {
                    model.list.ForEach(t =>
                    {
                        t.is_baoming = 1;
                        //出价价格
                        var chujia = dbcontext.ADZ_JingjiaSubmit
                        .OrderByDescending(sub => sub.seq_id)
                        .FirstOrDefault(sub => sub.uid == uid && sub.jingjia_id == t.jingjia_id);
                        if (chujia != null)
                        {
                            t.my_price = chujia.my_price;
                            //是否成交
                            t.is_hit = chujia.is_hit;
                            t.submit_status = chujia.status;
                        }
                    });
                }

                return new Tuple<bool, JingjiaListModel>(true, model);
            }
            else
                return new Tuple<bool, JingjiaListModel>(false, null);
        }

        /// <summary>
        /// 竞价详情查询
        /// </summary>
        /// <returns></returns>
        public Tuple<bool, JingjiaModel> GetInfo(long uid, long jingjia_id)
        {

            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
            ADZ_JingjiaMaster aDZ_JingjiaMaster = dbcontext.ADZ_JingjiaMaster.FirstOrDefault(t => t.jingjia_id == jingjia_id);
            if (aDZ_JingjiaMaster == null)
            {
                return new Tuple<bool, JingjiaModel>(false, null);
            }

            JingjiaModel jingjiaModel = new JingjiaModel();
            List<string> exp = new List<string>();
            Utils.Mapper(jingjiaModel, aDZ_JingjiaMaster, exp);
            jingjiaModel.img_url = SysConfigBiz.Instance.GetThingIMG(jingjiaModel.img_url);


            var jingjiafonfig = dbcontext.ADZ_JingjiaConfig.FirstOrDefault(t => t.jingjia_config_id == aDZ_JingjiaMaster.jingjia_config_id);
            if (jingjiafonfig != null)
            {
                jingjiaModel.baoming_counts = jingjiafonfig.baoming_counts;
                jingjiaModel.baozheng_price = jingjiafonfig.baozheng_price;
                jingjiaModel.begin_time = jingjiafonfig.begin_time;
                if (!jingjiaModel.real_end_time.HasValue)
                {
                    jingjiaModel.real_end_time = jingjiafonfig.end_time;
                }
            }


            //是否报名
            var baoming = dbcontext.ADZ_JingjiaBaomingOrder.FirstOrDefault(t => t.jingjia_config_id == aDZ_JingjiaMaster.jingjia_config_id && t.uid == uid && t.is_succ == 1);
            if (baoming != null)
            {
                jingjiaModel.is_baoming = 1;
                //出价价格
                var chujia = dbcontext.ADZ_JingjiaSubmit
                .OrderByDescending(sub => sub.seq_id)
                .FirstOrDefault(sub => sub.uid == uid && sub.jingjia_id == jingjia_id);
                if (chujia != null)
                {
                    jingjiaModel.my_price = chujia.my_price;
                    //是否成交
                    jingjiaModel.is_hit = chujia.is_hit;
                    jingjiaModel.submit_status = chujia.status;
                    jingjiaModel.order_master_id = chujia.order_master_id;
                    if (jingjiaModel.order_master_id > 0)
                    {
                        var ordermaster = dbcontext.ADZ_OrderMaster.FirstOrDefault(o => o.order_id == jingjiaModel.order_master_id);
                        if (ordermaster != null)
                        {
                            jingjiaModel.order_no = ordermaster.order_NO;
                        }
                    }
                }
            }

            aDZ_JingjiaMaster.weiguan_counts++;
            dbcontext.SaveChanges();

            return new Tuple<bool, JingjiaModel>(true, jingjiaModel);
        }

        /// <summary>
        /// 提交报名
        /// </summary>
        /// <returns></returns>
        public Tuple<bool, string, string> CreateBaoming(long uid, long jingjia_config_id)
        {
            if (uid <= 0)
                return new Tuple<bool, string, string>(false, "", "用户不存在，无法报名");

            string stroutput = string.Empty;
            string orderno = Utils.BuildOrderId("BM", 18);
            if (string.IsNullOrWhiteSpace(orderno))
                return new Tuple<bool, string, string>(false, "", "订单号生成失败，无法下单");

            string remark = string.Empty;
            string msg = string.Empty;

            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
            var jingjiaConfig = dbcontext.ADZ_JingjiaConfig.FirstOrDefault(t => t.jingjia_config_id == jingjia_config_id && t.is_del == 0 && t.is_show == 1);
            if (jingjiaConfig == null)
            {
                return new Tuple<bool, string, string>(false, "", "竞价信息有误，请重新提交。");
            }
            if (jingjiaConfig.jingjia_config_satus == 2 || jingjiaConfig.end_time <= DateTime.Now)
            {
                return new Tuple<bool, string, string>(false, "", "竞价已经结束，无法报名。");
            }

            var baoming = dbcontext.ADZ_JingjiaBaomingOrder.FirstOrDefault(t => t.jingjia_config_id == jingjia_config_id && t.uid == uid && t.is_succ == 1);
            if (baoming != null)
            {
                return new Tuple<bool, string, string>(false, "", "您已经报名，可以直接参与竞价。");
            }

            ADZ_JingjiaBaomingOrder baomingorder = new ADZ_JingjiaBaomingOrder
            {
                create_time = DateTime.Now,
                is_succ = 0,
                uid = uid,
                jingjia_config_id = jingjia_config_id,
                order_amt = jingjiaConfig.baozheng_price,
                order_status = 0,
                remark = "报名",
                order_NO = orderno
            };
            dbcontext.ADZ_JingjiaBaomingOrder.Add(baomingorder);
            dbcontext.SaveChanges();
            var data = new
            {
                seq_id = baomingorder.seq_id,
                order_no = baomingorder.order_NO,
                total_money = baomingorder.order_amt,
                create_time = baomingorder.create_time
            };
            //报名订单创建成功
            return new Tuple<bool, string, string>(true, JsonHelper.Serialize(data), "");
        }

        /// <summary>
        /// 报名支付支付交易订单 todo
        /// </summary>
        public Tuple<bool, string, string> PayBaomingOrder(long uid, string paypwd, string order_no, int pay_type)
        {

            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();

            string strResp = string.Empty;
            //判断用户
            var acc = AccountDataAccess.Instance.GetAccount(uid);
            if (acc == null)
                return new Tuple<bool, string, string>(false, strResp, "订单支付失败，用户不存在");

            if (acc.account_status != (int)AccountStatus.Normal)
                return new Tuple<bool, string, string>(false, strResp, "订单支付失败，用户异常");


            //判断支付密码
            if (pay_type == (int)PayType.Balance)
            {
                if (string.IsNullOrWhiteSpace(acc.pay_password))
                    return new Tuple<bool, string, string>(false, strResp, "订单支付失败，未设置支付密码");

                var checkResult = AccountBiz.Instance.CheckPayPwd(uid, acc.pay_password, paypwd);
                if (!checkResult.Item1)
                    return new Tuple<bool, string, string>(false, strResp, checkResult.Item2);
            }

            ADZ_JingjiaBaomingOrder baomingorder = dbcontext.ADZ_JingjiaBaomingOrder.FirstOrDefault(t => t.order_NO == order_no);
            if (baomingorder == null)
                return new Tuple<bool, string, string>(false, strResp, "订单支付失败，订单不存在");

            if (baomingorder.is_succ != 0)
                return new Tuple<bool, string, string>(false, strResp, "订单已经支付，无需再次支付");
            decimal amt = baomingorder.order_amt;


            var jongjiaconfig = dbcontext.ADZ_JingjiaConfig.FirstOrDefault(t => t.jingjia_config_id == baomingorder.jingjia_config_id && t.is_del == 0);
            if (jongjiaconfig == null)
                return new Tuple<bool, string, string>(false, strResp, "竞价信息有误，请检查之后重新提交");
            if (jongjiaconfig.jingjia_config_satus == 2 || jongjiaconfig.end_time <= DateTime.Now)
            {
                return new Tuple<bool, string, string>(false, "", "竞价已经结束，无法报名。");
            }

            PayOrderResp resp = new PayOrderResp();
            resp.amt = baomingorder.order_amt;
            resp.order_no = order_no;
            resp.pay_type = pay_type;
            resp.respData = "";
            if (pay_type == (int)PayType.Balance)
            {
                //余额支付，验证余额是否足够支付
                if (acc.account_balance < amt)
                    return new Tuple<bool, string, string>(false, strResp, "订单支付失败，余额不足");

                //支付-账户扣钱，修改交易订单状态等
                if (!BaomingPaySucc(baomingorder.seq_id, pay_type))
                {
                    return new Tuple<bool, string, string>(false, strResp, "支付失败");
                }
            }
            else if (pay_type == (int)PayType.Alipay)
            {
                //创建充值订单
                string zfbOrderId = Utils.BuildOrderId("CH", 20);
                string zfbBillNo = Utils.BuildOrderId("", 20);
                if (!OrderBiz.Instance.CreateChargeOrder(zfbOrderId, zfbBillNo, uid, (int)BusinessOrderType.BaomingOrder, baomingorder.seq_id, amt, (int)ChannelType.AlipayApp, "支付宝支付竞价保证金"))
                    return new Tuple<bool, string, string>(false, strResp, "订单支付失败，创建充值订单失败");

                //提交支付宝充值
                var zfbResult = AlipayBiz.DoSubmit(zfbBillNo, amt);
                if (!zfbResult.Item1)
                    return new Tuple<bool, string, string>(false, strResp, zfbResult.Item3);

                resp.respData = zfbResult.Item2;
            }
            else if (pay_type == (int)PayType.Wechat)
            {
                //创建充值订单
                string wxOrderId = Utils.BuildOrderId("CH", 20);
                string wxBillNo = Utils.BuildOrderId("", 20);
                if (!OrderBiz.Instance.CreateChargeOrder(wxOrderId, wxBillNo, uid, (int)BusinessOrderType.BaomingOrder, baomingorder.seq_id, amt, (int)ChannelType.WechatApp, "微信支付竞价保证金"))
                    return new Tuple<bool, string, string>(false, strResp, "订单支付失败，创建充值订单失败");

                //提交微信充值
                var wxResult = WechatBiz.BuildOrder(wxBillNo, amt);
                if (!wxResult.Item1)
                    return new Tuple<bool, string, string>(false, strResp, wxResult.Item3);

                resp.respData = wxResult.Item2;
            }
            else
                return new Tuple<bool, string, string>(false, strResp, "订单支付失败，支付方式错误");

            strResp = JsonHelper.Serialize(resp);
            return new Tuple<bool, string, string>(true, strResp, "");
        }


        /// <summary>
        /// 报名支付成功
        /// </summary>
        /// <param name="pay_type">2 余额 3 支付宝 4 微信</param>
        /// <returns></returns>
        public bool BaomingPaySucc(long seq_id, int pay_type)
        {
            try
            {
                ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
                string stroutput = string.Empty;
                if (seq_id <= 0)
                {
                    LogHelper.Error("交易订单更新失败,方法参数错误");
                    return false;
                }
                //int ret = OrderDataAccess.Instance.OrderPaySucc(order_id, pay_type, out stroutput);

                ADZ_JingjiaBaomingOrder baomingorder = dbcontext.ADZ_JingjiaBaomingOrder.FirstOrDefault(t => t.seq_id == seq_id);
                if (baomingorder == null)
                {
                    LogHelper.Error($"报名seq_id={seq_id}不存在");
                    return false;
                }
                if (baomingorder.is_succ == 0)
                {
                    //1、扣除余额
                    var chargemaster = dbcontext.ADZ_ChargeMaster.FirstOrDefault(t => t.uid == baomingorder.uid);
                    if (chargemaster == null)
                    {
                        LogHelper.Error($"用户UID={baomingorder.uid}不存在");
                        return false;
                    }
                    if (chargemaster.account_balance < baomingorder.order_amt)
                    {
                        LogHelper.Error($"用户UID={baomingorder.uid}余额不足以支付报名{baomingorder.seq_id}");
                        return false;
                    }
                    var jingjiaconfig = dbcontext.ADZ_JingjiaConfig.FirstOrDefault(t => t.jingjia_config_id == baomingorder.jingjia_config_id && t.is_del == 0);
                    if (jingjiaconfig == null)
                    {
                        LogHelper.Error($"竞价jingjia_config_id={jingjiaconfig.jingjia_config_id}不存在");
                        return false;
                    }

                    if (chargemaster.charge_balance >= baomingorder.order_amt)
                    {
                        chargemaster.account_balance = chargemaster.account_balance - baomingorder.order_amt;
                        chargemaster.charge_balance = chargemaster.charge_balance - baomingorder.order_amt;
                    }
                    else
                    {
                        chargemaster.account_balance = chargemaster.account_balance - baomingorder.order_amt;
                        chargemaster.give_balance -= (baomingorder.order_amt - chargemaster.charge_balance);
                        chargemaster.charge_balance = 0;
                    }

                    dbcontext.ADZ_AmountLog.Add(new ADZ_AmountLog
                    {
                        amount = baomingorder.order_amt,
                        create_time = DateTime.Now,
                        inOrOut = 1,
                        is_show = 0,
                        message = "竞价支付保证金",
                        orderid = baomingorder.order_NO,
                        order_type = 3,
                        remark = "竞价支付保证金",
                        uid = baomingorder.uid
                    });
                    baomingorder.pay_type = (byte)pay_type;
                    baomingorder.is_succ = 1;
                    baomingorder.succ_time = DateTime.Now;
                    baomingorder.order_status = 1;
                    jingjiaconfig.baoming_counts += 1;

                    dbcontext.SaveChanges();


                    var userinfo = dbcontext.ADZ_MemberMaster.FirstOrDefault(t => t.uid == baomingorder.uid);

                    //发送业务消息
                    BusinessMsgBiz.Instance.SendBusinessMsg(new ADZ_BusinessMsg
                    {
                        BusinessMsgType = (int)BusinessMsgEnum.JingjiaBaoming,
                        msg = $"竞价报名支付成功，用户名{ userinfo.member_name }，手机号{ userinfo.account_mobile }，本次付款金额：￥{baomingorder.order_amt}",
                        msg_title = "竞价报名支付成功",
                        //todo msg_url = $"/OrderMaster/OrderMasterInfo/{order_master.order_id}"
                    });
                    //发送推送消息
                    AddPushMsgModel paramModel = new AddPushMsgModel
                    {
                        aDZ_Pushmessage = new ADZ_Pushmessage
                        {
                            MsgType = 2,
                            ReceiveType = 1,
                            MsgTitle = "竞价报名支付成功",
                            MsgText = $"您的竞价报名成功，本次付款金额：￥{baomingorder.order_amt}。"
                        },
                        ReceiveUids = baomingorder.uid.ToString()
                    };
                    PushMsgBiz.Instance.AddPushMsg(paramModel);

                    if (userinfo != null)
                    {
                        JingjiaBiz.Instance.WriteOrderLog(new ADZ_JingjiaMasterLog
                        {
                            jingjia_id = jingjiaconfig.jingjia_config_id,
                            op_msg = $"用户报名成功，用户名{userinfo.member_name},手机号{userinfo.account_mobile}",
                            uid = baomingorder.uid,
                            op_user = userinfo.account_mobile
                        });
                    }
                }
            }
            catch (Exception e)
            {
                LogHelper.Fatal("交易订单更新失败：" + e.GetExcetionMessage());
                return false;
            }
            return true;
        }

        /// <summary>
        /// 用户报价
        /// </summary>
        /// <param name="pay_type">2 余额 3 支付宝 4 微信</param>
        /// <returns></returns>
        public Tuple<bool, string, string> JingjiaSubmt(long uid, long jingjia_id, decimal my_price)
        {
            try
            {
                ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
                string stroutput = string.Empty;
                if (uid <= 0 || jingjia_id <= 0 || my_price <= 0)
                {
                    LogHelper.Error("报价失败,方法参数错误");
                    return new Tuple<bool, string, string>(false, "", "报价失败,方法参数错误");
                }

                var userinfo = dbcontext.ADZ_MemberMaster.FirstOrDefault(t => t.uid == uid);
                if (userinfo == null)
                {
                    return new Tuple<bool, string, string>(false, "", $"用户信息不正确");
                }

                var jingjiamaster = dbcontext.ADZ_JingjiaMaster.FirstOrDefault(t => t.jingjia_id == jingjia_id && t.is_del == 0);
                if (jingjiamaster == null)
                {
                    return new Tuple<bool, string, string>(false, "", $"竞价jingjia_id={jingjiamaster.jingjia_id}不存在");
                }
                if (jingjiamaster.jingjia_satus == 0)
                {
                    return new Tuple<bool, string, string>(false, "", "竞价还未开始，请耐心等待。");
                }

                if (jingjiamaster.jingjia_satus != 1)
                {
                    return new Tuple<bool, string, string>(false, "", "竞价已经结束，无法提交报价。");
                }
                DateTime? endtime = jingjiamaster.real_end_time;
                if (!endtime.HasValue)
                {
                    var config = dbcontext.ADZ_JingjiaConfig.First(t => t.jingjia_config_id == jingjiamaster.jingjia_config_id);
                    endtime = config.end_time;
                }
                if (endtime.Value < DateTime.Now)
                {
                    return new Tuple<bool, string, string>(false, "", "竞价已经结束，无法提交报价。");
                }


                ADZ_JingjiaBaomingOrder baomingorder = dbcontext.ADZ_JingjiaBaomingOrder.FirstOrDefault(t => t.jingjia_config_id == jingjiamaster.jingjia_config_id && t.uid == uid && t.is_succ == 1);
                if (baomingorder == null)
                {
                    return new Tuple<bool, string, string>(false, "", "对不起，您还没有报名无法参与竞价。");
                }

                var last_amount = jingjiamaster.last_price;
                //当前价为0
                if (last_amount <= 0)
                {
                    //起拍价为0
                    if (jingjiamaster.base_price == 0)
                    {
                        //出价不能少于幅度
                        if (jingjiamaster.step_price > my_price)
                        {
                            return new Tuple<bool, string, string>(false, "", $"出价金额不能少于{Math.Round(jingjiamaster.step_price, 2)}。");
                        }
                    }
                    else
                    {
                        //出价不能少于起拍价
                        if (jingjiamaster.base_price > my_price)
                        {
                            return new Tuple<bool, string, string>(false, "", $"出价金额不能少于{Math.Round(jingjiamaster.base_price, 2)}。");
                        }
                    }
                }
                else if (last_amount + jingjiamaster.step_price > my_price)
                {
                    return new Tuple<bool, string, string>(false, "", $"出价金额不能少于{Math.Round(last_amount + jingjiamaster.step_price, 2)}。");
                }

                if (jingjiamaster.step_price_max > jingjiamaster.step_price)
                {
                    if (last_amount <= 0)
                    {
                        //出价不能大于起拍价+最大幅度
                        if (jingjiamaster.base_price + jingjiamaster.step_price_max < my_price)
                        {
                            return new Tuple<bool, string, string>(false, "", $"出价金额不能多于{Math.Round(jingjiamaster.base_price + jingjiamaster.step_price_max, 2)}。");
                        }
                    }
                    else if (my_price > last_amount + jingjiamaster.step_price_max)
                    {
                        return new Tuple<bool, string, string>(false, "", $"出价金额不能多于{Math.Round(last_amount + jingjiamaster.step_price_max, 2)}。");
                    }
                }

                jingjiamaster.chujia_counts += 1;
                jingjiamaster.last_price = my_price;
                jingjiamaster.last_time = DateTime.Now;
                jingjiamaster.last_uid = uid;
                jingjiamaster.last_username = dbcontext.ADZ_MemberMaster.First(t => t.uid == uid).account_mobile;

                var jingjiaconfig = dbcontext.ADZ_JingjiaConfig.FirstOrDefault(t => t.jingjia_config_id == jingjiamaster.jingjia_config_id);
                if (!jingjiamaster.real_end_time.HasValue)
                {
                    ///当前时间加5分钟后已经超过结束时间，则结束时间需要顺延
                    if (DateTime.Now.AddMinutes(jingjiamaster.stay_miniutes) > jingjiaconfig.end_time)
                    {
                        jingjiamaster.real_end_time = DateTime.Now.AddMinutes(jingjiamaster.stay_miniutes);
                    }
                }
                else if (DateTime.Now.AddMinutes(jingjiamaster.stay_miniutes) > jingjiamaster.real_end_time.Value)
                {
                    jingjiamaster.real_end_time = DateTime.Now.AddMinutes(jingjiamaster.stay_miniutes);
                }

                if (DateTime.Now.AddMinutes(jingjiamaster.stay_miniutes) > jingjiaconfig.end_time)
                {
                    jingjiaconfig.end_time = DateTime.Now.AddMinutes(jingjiamaster.stay_miniutes);
                }

                //修改之前的出价为被超越
                var chujialist = dbcontext.ADZ_JingjiaSubmit.Where(t => t.jingjia_id == jingjia_id && t.is_del == 0).ToList();
                if (chujialist.Any())
                {
                    chujialist.ForEach(
                        t =>
                        {
                            if (t.uid != uid && t.status == 0)
                            {
                                t.status = 1;
                                t.over_time = DateTime.Now;
                                string message = $"【爱电子】您参与的竞价【{jingjiamaster.jingjia_name}】已于{DateTime.Now.ToString(1)}被超越，当前出价金额￥{Math.Round(my_price, 2)}。";
                                //发短信通知用户
                                if(t.uid > 0)
                                {
                                    var c_user = dbcontext.ADZ_MemberMaster.FirstOrDefault(x => x.uid == t.uid);
                                    SmsBiz.Instance.SendMessage(c_user.account_mobile, message);
                                    //发送推送消息
                                    AddPushMsgModel pushModel = new AddPushMsgModel
                                    {
                                        aDZ_Pushmessage = new ADZ_Pushmessage
                                        {
                                            MsgType = 2,
                                            ReceiveType = 1,
                                            MsgTitle = "竞价被超",
                                            MsgText = message.Replace("【爱电子】", "")
                                        },
                                        ReceiveUids = t.uid.ToString()
                                    };
                                    PushMsgBiz.Instance.AddPushMsg(pushModel);
                                }                               
                            }
                            else
                            {
                                if (t.uid == uid)
                                {
                                    t.is_del = 1;
                                }
                                if (t.status == 0)
                                {
                                    t.status = 1;
                                    t.over_time = DateTime.Now;
                                }
                            }
                        });
                }

                ADZ_JingjiaSubmit aDZ_JingjiaSubmit = new ADZ_JingjiaSubmit
                {
                    create_time = DateTime.Now,
                    is_del = 0,
                    is_hit = 0,
                    jingjia_id = jingjia_id,
                    status = 0,
                    my_price = my_price,
                    uid = uid,
                    username = userinfo.account_mobile

                };
                dbcontext.ADZ_JingjiaSubmit.Add(aDZ_JingjiaSubmit);
                dbcontext.SaveChanges();

                WriteOrderLog(
                    new ADZ_JingjiaMasterLog
                    {
                        jingjia_id = jingjia_id,
                        op_msg = $"用户出价{my_price}",
                        op_user = userinfo.account_mobile,
                        uid = uid
                    });
                return new Tuple<bool, string, string>(true, "出价成功", "出价成功");
            }
            catch (Exception ex)
            {
                LogHelper.Error("记录竞价日志：" + ex.GetExcetionMessage());
                return new Tuple<bool, string, string>(false, "", $"发生异常{ex.GetExcetionMessage()}");
            }
        }

        public void WriteOrderLog(ADZ_JingjiaMasterLog log)
        {
            try
            {
                log.create_time = DateTime.Now;
                ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
                dbcontext.ADZ_JingjiaMasterLog.Add(log);
                dbcontext.SaveChanges();
            }
            catch (Exception ex)
            {
                LogHelper.Error("记录竞价日志：" + ex.GetExcetionMessage());
            }
        }


        #region 同步AB系统竞价信息



        /// <summary>
        /// 报名同步
        /// </summary>
        public Tuple<bool, string, string> AsyncBaomingOrder(string username)
        {

            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();

            var config = dbcontext.ADZ_JingjiaConfig.FirstOrDefault(t => t.is_show == 1);
            if (config != null)
            {
                config.baoming_counts++;
            }
            dbcontext.SaveChanges();
            return new Tuple<bool, string, string>(true, "", "");
        }

        /// <summary>
        /// 用户报价
        /// </summary>
        /// <param name="pay_type">2 余额 3 支付宝 4 微信</param>
        /// <returns></returns>
        public Tuple<bool, string, string> AsyncJingjiaSubmt(string username,string jingjianame,decimal my_price)
        {
            try
            {
                ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();

                var jingjiamaster = dbcontext.ADZ_JingjiaMaster.FirstOrDefault(t => t.jingjia_name == jingjianame);
                if(jingjiamaster == null)
                {
                    string msg = $"外部系统同步报价[{jingjianame}]不存在";
                    LogHelper.Error(msg);
                    return new Tuple<bool, string, string>(false, "", msg);
                }
                
                if (jingjiamaster.jingjia_satus == 0)
                {
                    return new Tuple<bool, string, string>(false, "", "竞价还未开始，请耐心等待。");
                }

                if (jingjiamaster.jingjia_satus != 1)
                {
                    return new Tuple<bool, string, string>(false, "", "竞价已经结束，无法提交报价。");
                }
                DateTime? endtime = jingjiamaster.real_end_time;
                if (!endtime.HasValue)
                {
                    var config = dbcontext.ADZ_JingjiaConfig.First(t => t.jingjia_config_id == jingjiamaster.jingjia_config_id);
                    endtime = config.end_time;
                }
                if (endtime.Value < DateTime.Now)
                {
                    return new Tuple<bool, string, string>(false, "", "竞价已经结束，无法提交报价。");
                }

                var last_amount = jingjiamaster.last_price;
                //当前价为0
                if (last_amount <= 0)
                {
                    //起拍价为0
                    if (jingjiamaster.base_price == 0)
                    {
                        //出价不能少于幅度
                        if (jingjiamaster.step_price > my_price)
                        {
                            return new Tuple<bool, string, string>(false, "", $"出价金额不能少于{Math.Round(jingjiamaster.step_price, 2)}。");
                        }
                    }
                    else
                    {
                        //出价不能少于起拍价
                        if (jingjiamaster.base_price > my_price)
                        {
                            return new Tuple<bool, string, string>(false, "", $"出价金额不能少于{Math.Round(jingjiamaster.base_price, 2)}。");
                        }
                    }
                }
                else if (last_amount + jingjiamaster.step_price > my_price)
                {
                    return new Tuple<bool, string, string>(false, "", $"出价金额不能少于{Math.Round(last_amount + jingjiamaster.step_price, 2)}。");
                }

                if (jingjiamaster.step_price_max > jingjiamaster.step_price)
                {
                    if (last_amount <= 0)
                    {
                        //出价不能大于起拍价+最大幅度
                        if (jingjiamaster.base_price + jingjiamaster.step_price_max < my_price)
                        {
                            return new Tuple<bool, string, string>(false, "", $"出价金额不能多于{Math.Round(jingjiamaster.base_price + jingjiamaster.step_price_max, 2)}。");
                        }
                    }
                    else if (my_price > last_amount + jingjiamaster.step_price_max)
                    {
                        return new Tuple<bool, string, string>(false, "", $"出价金额不能多于{Math.Round(last_amount + jingjiamaster.step_price_max, 2)}。");
                    }
                }

                jingjiamaster.chujia_counts += 1;
                jingjiamaster.last_price = my_price;
                jingjiamaster.last_time = DateTime.Now;
                jingjiamaster.last_uid = 0;
                jingjiamaster.last_username = username;

                var jingjiaconfig = dbcontext.ADZ_JingjiaConfig.FirstOrDefault(t => t.jingjia_config_id == jingjiamaster.jingjia_config_id);
                if (!jingjiamaster.real_end_time.HasValue)
                {
                    ///当前时间加5分钟后已经超过结束时间，则结束时间需要顺延
                    if (DateTime.Now.AddMinutes(jingjiamaster.stay_miniutes) > jingjiaconfig.end_time)
                    {
                        jingjiamaster.real_end_time = DateTime.Now.AddMinutes(jingjiamaster.stay_miniutes);
                    }
                }
                else if (DateTime.Now.AddMinutes(jingjiamaster.stay_miniutes) > jingjiamaster.real_end_time.Value)
                {
                    jingjiamaster.real_end_time = DateTime.Now.AddMinutes(jingjiamaster.stay_miniutes);
                }

                if (DateTime.Now.AddMinutes(jingjiamaster.stay_miniutes) > jingjiaconfig.end_time)
                {
                    jingjiaconfig.end_time = DateTime.Now.AddMinutes(jingjiamaster.stay_miniutes);
                }

                long jingjia_id = jingjiamaster.jingjia_id;
                long uid = 0;
                //修改之前的出价为被超越
                var chujialist = dbcontext.ADZ_JingjiaSubmit.Where(t => t.jingjia_id == jingjia_id && t.is_del == 0).ToList();
                if (chujialist.Any())
                {
                    chujialist.ForEach(
                        t =>
                        {
                            if (t.uid != uid && t.status == 0)
                            {
                                t.status = 1;
                                t.over_time = DateTime.Now;
                                string message = $"【爱电子】您参与的竞价【{jingjiamaster.jingjia_name}】已于{DateTime.Now.ToString(1)}被超越，当前出价金额￥{Math.Round(my_price, 2)}。";
                                //发短信通知用户
                                if (t.uid > 0)
                                {
                                    var c_user = dbcontext.ADZ_MemberMaster.FirstOrDefault(x => x.uid == t.uid);
                                    SmsBiz.Instance.SendMessage(c_user.account_mobile, message);
                                    //发送推送消息
                                    AddPushMsgModel pushModel = new AddPushMsgModel
                                    {
                                        aDZ_Pushmessage = new ADZ_Pushmessage
                                        {
                                            MsgType = 2,
                                            ReceiveType = 1,
                                            MsgTitle = "竞价被超",
                                            MsgText = message.Replace("【爱电子】", "")
                                        },
                                        ReceiveUids = t.uid.ToString()
                                    };
                                    PushMsgBiz.Instance.AddPushMsg(pushModel);
                                }
                            }
                            else
                            {
                                if (t.uid == uid)
                                {
                                    t.is_del = 1;
                                }
                                if (t.status == 0)
                                {
                                    t.status = 1;
                                    t.over_time = DateTime.Now;
                                }
                            }
                        });
                }

                ADZ_JingjiaSubmit aDZ_JingjiaSubmit = new ADZ_JingjiaSubmit
                {
                    create_time = DateTime.Now,
                    is_del = 0,
                    is_hit = 0,
                    jingjia_id = jingjia_id,
                    status = 0,
                    my_price = my_price,
                    uid = uid,
                    username = username

                };
                dbcontext.ADZ_JingjiaSubmit.Add(aDZ_JingjiaSubmit);
                dbcontext.SaveChanges();

                WriteOrderLog(
                    new ADZ_JingjiaMasterLog
                    {
                        jingjia_id = jingjia_id,
                        op_msg = $"外部系统同步出价{my_price}",
                        op_user = username,
                        uid = uid
                    });
                return new Tuple<bool, string, string>(true, "出价成功", "出价成功");
            }
            catch (Exception ex)
            {
                LogHelper.Error("记录竞价日志：外部系统同步 " + ex.GetExcetionMessage());
                return new Tuple<bool, string, string>(false, "", $"发生异常{ex.GetExcetionMessage()}");
            }
        }

        #endregion

    }
}
